{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "4dcfc970",
   "metadata": {},
   "source": [
    "<a href=\"https://colab.research.google.com/github/run-llama/llama_index/blob/main/docs/examples/llm/cometapi.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e2d94324",
   "metadata": {},
   "source": [
    "# CometAPI\n",
    "\n",
    "CometAPI provides access to various state-of-the-art LLM models including GPT series, Claude series, Gemini series, and more through a unified OpenAI-compatible interface. You can find out more on their [homepage](https://www.cometapi.com/).\n",
    "\n",
    "Visit https://api.cometapi.com/console/token to sign up and get an API key.\n",
    "\n",
    "If you're opening this Notebook on colab, you will probably need to install LlamaIndex 🦙."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "39bcb78b",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index-llms-cometapi"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "41803b12",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install llama-index"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "69a0b454",
   "metadata": {},
   "outputs": [],
   "source": [
    "from llama_index.llms.cometapi import CometAPI"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e321b53a",
   "metadata": {},
   "source": [
    "## Call `chat` with ChatMessage List\n",
    "You need to either set env var `COMETAPI_API_KEY` or set api_key in the class constructor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5cf1fa70",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "os.environ[\"COMETAPI_KEY\"] = \"<your-cometapi-key>\"\n",
    "\n",
    "api_key = os.getenv(\"COMETAPI_KEY\")\n",
    "llm = CometAPI(\n",
    "    api_key=api_key,\n",
    "    max_tokens=256,\n",
    "    context_window=4096,\n",
    "    model=\"gpt-5-chat-latest\",\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "259e7feb",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "assistant: Hi\n"
     ]
    }
   ],
   "source": [
    "from llama_index.core.llms import ChatMessage\n",
    "\n",
    "messages = [\n",
    "    ChatMessage(role=\"system\", content=\"You are a helpful assistant\"),\n",
    "    ChatMessage(role=\"user\", content=\"Say 'Hi' only!\"),\n",
    "]\n",
    "resp = llm.chat(messages)\n",
    "print(resp)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c316d6f4",
   "metadata": {},
   "outputs": [],
   "source": [
    "resp = llm.complete(\"Who is Kaiming He\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "fa8079b9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Kaiming He is a renowned computer scientist and research scientist known for his influential contributions to the field of computer vision and deep learning. He is particularly famous for being one of the main authors of the **ResNet** (Residual Networks) architecture, introduced in the 2015 paper *\"Deep Residual Learning for Image Recognition\"*, which won the Best Paper Award at CVPR 2016. ResNet significantly improved the training of very deep neural networks using residual connections, and it became a foundational architecture for many vision tasks.\n",
      "\n",
      "### Key Facts about Kaiming He:\n",
      "\n",
      "- **Education**:  \n",
      "  Kaiming He earned his Ph.D. in computer science from the Chinese University of Hong Kong (CUHK), where he worked with Prof. Jian Sun and in collaboration with the Visual Computing Group.\n",
      "\n",
      "- **Research Career**:\n",
      "  - He has worked at Microsoft Research Asia (MSRA).\n",
      "  - Later, he was a research scientist at Facebook AI Research (FAIR).\n",
      "  - As of recent years, he works at FAIR (now part of Meta AI) focusing on computer vision, deep learning, and artificial intelligence.\n",
      "\n",
      "- **Major Contributions**:\n",
      "  - **ResNet** (Deep Residual Networks, 2015) — revolutionized deep network\n"
     ]
    }
   ],
   "source": [
    "print(resp)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e7c7a7b3",
   "metadata": {},
   "source": [
    "### Streaming"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "437a268e",
   "metadata": {},
   "source": [
    "Using `stream_complete` endpoint "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ed59c4b7",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ResNet, short for **Residual Network**, is a type of deep neural network architecture introduced by Microsoft Research in 2015 in the paper *\"Deep Residual Learning for Image Recognition\"* by Kaiming He et al. It became famous after winning the **ImageNet Large Scale Visual Recognition Challenge ( al. It became famous after winning the **ImageNet Large Scale Visual Recognition Challenge (ILSVRC) 2015**.\n",
      "\n",
      "---\n",
      "\n",
      "### **Key idea**\n",
      "The main innovation of ResNet isILSVRC) 2015**.\n",
      "\n",
      "---\n",
      "\n",
      "### **Key idea**\n",
      "The main innovation of ResNet is the concept of **residual learning** using **skip connections** (or shortcut connections). In very the concept of **residual learning** using **skip connections** (or shortcut connections). In very deep neural networks, performance can degrade because of the **vanishing/exploding gradient problem deep neural networks, performance can degrade because of the **vanishing/exploding gradient problem** and difficulty in optimization. ResNet solves this by letting certain layers \"skip\" forward in** and difficulty in optimization. ResNet solves this by letting certain layers \"skip\" forward in the network through identity mappings.\n",
      "\n",
      "A *residual block the network through identity mappings.\n",
      "\n",
      "A *residual block* looks like this:\n",
      "\n",
      "```\n",
      "Input → [Layer(s): Conv, BatchNorm* looks like this:\n",
      "\n",
      "```\n",
      "Input → [Layer(s): Conv, BatchNorm, ReLU] → Output\n",
      "   \\_____________________________________/\n",
      "                  (skip, ReLU] → Output\n",
      "   \\_____________________________________/\n",
      "                  (skip connection)\n",
      "```\n",
      "\n",
      "Instead of directly learning a mapping connection)\n",
      "```\n",
      "\n",
      "Instead of directly learning a mapping \\( H(x) \\), the residual block learns \\( F(x) \\( H(x) \\), the residual block learns \\( F(x) = H(x) - x \\), so that:\n",
      "\\[\n",
      "H(x) = F(x) + x\n",
      "\\]\n",
      "Here = H(x) - x \\), so that:\n",
      "\\[\n",
      "H(x) = F(x) + x\n",
      "\\]\n",
      "Here, \\( x \\) is added directly to the output of the block, enabling easier gradient flow, \\( x \\) is added directly to the output of the block, enabling easier gradient flow and allowing training of and allowing training of"
     ]
    }
   ],
   "source": [
    "message = ChatMessage(role=\"user\", content=\"Tell me what ResNet is\")\n",
    "resp = llm.stream_chat([message])\n",
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "bf401630",
   "metadata": {},
   "outputs": [],
   "source": [
    "resp = llm.stream_complete(\"Tell me about Large Language Models\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d06ac632",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sure! **Large Language Models** (LLMs) are a type of **artificial intelligence model** designed to understand, generate, and manipulate human language. They’re trained on massive amounts of text from books, articles, websites, code** designed to understand, generate, and manipulate human language. They’re trained on massive amounts of text from books, articles, websites, code, and more, enabling them to predict and produce coherent text based on a prompt.\n",
      "\n",
      "Here’s a detailed, and more, enabling them to predict and produce coherent text based on a prompt.\n",
      "\n",
      "Here’s a detailed overview:\n",
      "\n",
      "---\n",
      "\n",
      "## **1. What They Are**\n",
      "- LLMs are a subset of ** overview:\n",
      "\n",
      "---\n",
      "\n",
      "## **1. What They Are**\n",
      "- LLMs are a subset of **deep learning** models, usually based on the **transformer architecture** (introduced in 2017deep learning** models, usually based on the **transformer architecture** (introduced in 2017 by *Vaswani et al.* in the paper *\"Attention Is All You Need\"*).\n",
      "- They are called * by *Vaswani et al.* in the paper *\"Attention Is All You Need\"*).\n",
      "- They are called *“large”* because they have **billions—or even trillions—of parameters** (adjustable weights“large”* because they have **billions—or even trillions—of parameters** (adjustable weights learned during training) and train on vast datasets.\n",
      "\n",
      "---\n",
      "\n",
      "## **2. How They Work**\n",
      "1. **Training Data learned during training) and train on vast datasets.\n",
      "\n",
      "---\n",
      "\n",
      "## **2. How They Work**\n",
      "1. **Training Data**  \n",
      "   They learn patterns of language from huge text corpora taken from books, Wikipedia, the internet, etc**  \n",
      "   They learn patterns of language from huge text corpora taken from books, Wikipedia, the internet, etc.\n",
      "2. **Tokenization**  \n",
      "   Text is broken into small pieces called *tokens* (these.\n",
      "2. **Tokenization**  \n",
      "   Text is broken into small pieces called *tokens* (these could be whole words, subwords, or even characters).\n",
      "3. **Neural Architecture**  \n",
      "   could be whole words, subwords, or even characters).\n",
      "3. **Neural Architecture**  \n",
      "   Transformers use *self-attention* mechanisms to relate different Transformers use *self-attention* mechanisms to relate different"
     ]
    }
   ],
   "source": [
    "for r in resp:\n",
    "    print(r.delta, end=\"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a485d24f",
   "metadata": {},
   "source": [
    "### Using Different Models\n",
    "\n",
    "CometAPI supports various AI models including GPT, Claude, and Gemini series."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dcb08318",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "# Deep Learning: A Brief Explanation\n",
      "\n",
      "Deep learning is a subset of machine learning that uses neural networks with multiple layers (hence \"deep\") to analyze data and make predictions.\n",
      "\n",
      "## Key Characteristics:\n",
      "\n",
      "- **Neural Networks**: Inspired by the human brain, these networks consist of interconnected nodes (neurons) organized in layers\n",
      "- **Automatic Feature Extraction**: Unlike traditional ML, deep learning automatically discovers important features in data without manual engineering\n",
      "- **Hierarchical Learning**: Lower layers learn simple patterns while deeper layers combine these to recognize complex concepts\n",
      "- **Large Data Requirements**: Typically needs substantial amounts of data to perform well\n",
      "\n",
      "Deep learning powers many modern technologies including image recognition, natural language processing, speech recognition, and recommendation systems. Its effectiveness comes from its ability to model highly complex relationships in data, though this often requires significant computational resources.\n"
     ]
    }
   ],
   "source": [
    "# Using Claude model\n",
    "claude_llm = CometAPI(\n",
    "    api_key=api_key, model=\"claude-3-7-sonnet-latest\", max_tokens=200\n",
    ")\n",
    "\n",
    "resp = claude_llm.complete(\"Explain deep learning briefly\")\n",
    "print(resp)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "llama_index",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
